package com.glory.hikvisionmobile.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.GraphiteBoatAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.TrackOut.GraphiteBindListBean;
import com.glory.hikvisionmobile.bean.TrackOut.TrackOutLoadBean;
import com.glory.hikvisionmobile.bean.TrackOut.TrackOutSubmitBean;
import com.glory.hikvisionmobile.bean.TrackOut.XGrapHiteBoatBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.DialogUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class Work_GraphiteBoatTrackOutActivity extends BaseActivity {


    @BindView(R.id.tvLot)
    TextView tvLot;
    @BindView(R.id.tvMainWork)
    TextView tvMainWork;
    @BindView(R.id.tvLotNum)
    TextView tvLotNum;
    @BindView(R.id.tvCurrentStep)
    TextView tvCurrentStep;
    @BindView(R.id.etRemarks)
    FreeUI_ClearEditText etRemarks;
    @BindView(R.id.etCarrier)
    FreeUI_ClearEditText etCarrier;
    @BindView(R.id.tvAdd)
    TextView tvAdd;
    @BindView(R.id.rvGraphiteBoatList)
    RecyclerView rvGraphiteBoatList;
    @BindView(R.id.bottom_tv1)
    TextView bottomTv1;
    @BindView(R.id.bottom_tv2)
    TextView bottomTv2;
    @BindView(R.id.bottom_tv3)
    TextView bottomTv3;
    @BindView(R.id.bottom_tv4)
    TextView bottomTv4;
    @BindView(R.id.bottom_btn_layout)
    LinearLayout bottomBtnLayout;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.list_tv5)
    TextView listTv5;
    @BindView(R.id.list_tv6)
    TextView listTv6;
    @BindView(R.id.list_tv7)
    TextView listTv7;
    @BindView(R.id.list_tv8)
    TextView listTv8;
    @BindView(R.id.list_titleLayout)
    LinearLayout listTitleLayout;

    private String lotNum;
    private TrackOutLoadBean trackOutLoadBean;
    private GraphiteBoatAdapter graphiteBoatAdapter;
    private int position = 0;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_graphite_boat_track_out;
    }

    @Override
    protected void initView() {
        initInclude();
        Bundle bundle = getIntent().getExtras();
        lotNum = bundle.getString("lotNum");
        tvLot.setText(lotNum);


        rvGraphiteBoatList.setLayoutManager(new LinearLayoutManager(Work_GraphiteBoatTrackOutActivity.this));
        rvGraphiteBoatList.setItemAnimator(new DefaultItemAnimator());
        rvGraphiteBoatList.addItemDecoration(new DividerItemDecoration(Work_GraphiteBoatTrackOutActivity.this, 1));
        graphiteBoatAdapter = new GraphiteBoatAdapter(null);
        graphiteBoatAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        graphiteBoatAdapter.isFirstOnly(true);
        rvGraphiteBoatList.setAdapter(graphiteBoatAdapter);

    }

    @Override
    protected void initData() {

        JsonObject map = new JsonObject();
        map.addProperty("actionType", "Check");
        map.addProperty("lotId", lotNum);
        NetUtils.requestDara("HIK.PdaTrackOutLoad", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<TrackOutLoadBean>>(
                new TypeToken<BaseResponseBean<TrackOutLoadBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<TrackOutLoadBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    trackOutLoadBean = response.body().getBody();
                    tvMainWork.setText(trackOutLoadBean.getMainEquipments());
                    tvCurrentStep.setText(trackOutLoadBean.getCurrentStepDesc());
                    tvLotNum.setText(String.valueOf(trackOutLoadBean.getMainQty()));
                    if (!FreeApi_StringUtils.isEmpty(trackOutLoadBean.getGraphiteBoatStr())){
                        tvAdd.setEnabled(false);
                        bottomTv2.setEnabled(false);
                        bottomTv3.setEnabled(false);
                        bottomTv2.setBackgroundColor(getResources().getColor(R.color.free_ui_blue_sky_text_gray));
                        bottomTv3.setBackgroundColor(getResources().getColor(R.color.free_ui_blue_sky_text_gray));
                        tvAdd.setBackgroundColor(getResources().getColor(R.color.free_ui_blue_sky_text_gray));
                    }
//                    for (int i = 0; i < trackOutLoadBean.getxGrapHiteBoats().size(); i++) {
//                        XGrapHiteBoatBean bean = new XGrapHiteBoatBean();
//                        bean.setGraphiteCarrierId(trackOutLoadBean.getDurableId());
//                        bean.setGraphiteCarrierSeq(trackOutLoadBean.getxGrapHiteBoats().get(i).getGraphiteCarrierSeq());
//                        xGrapHiteBoatBean.add(bean);
//                    }
                    graphiteBoatAdapter.setNewData(trackOutLoadBean.getxGrapHiteBoats());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<TrackOutLoadBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaTrackOutLoad");

            }
        });

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("石墨舟待出站");
        return new FreeUI_AddViewEntity("header", llMain);
    }


    @OnClick({R.id.tvAdd, R.id.bottom_tv1, R.id.bottom_tv3,R.id.bottom_tv2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvAdd:
                initPermission("Add", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        if (editIsEmpty(etCarrier,"载具号不能为空")) {
                            searchCarrier(etCarrier.getText().toString().trim(),"add");
                        }
                    }
                });
                break;
            case R.id.bottom_tv1:

//                if (position != xGrapHiteBoatBeans.size()){
//                    showConfirmDialog("批次数量和石墨舟数量不一致无法出站");
//                    return;
//                }

//                if (graphiteBoatAdapter.getData().get(position - 1).getReleaseCarrierId().length() <= 0){
//                    showConfirmDialog("石墨舟未绑定载具，无法出站");
//                    return;
//                }
                initPermission("TrackOut", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        submit("Comment","HIK.PdaTrackOut");
                    }
                });
                break;
            case R.id.bottom_tv3:

//                if (xGrapHiteBoatBeans.size() > 0){
//                    showConfirmDialog("石墨舟已绑定载具，解绑后退站");
//                    return;
//                }
                initPermission("TrackExit", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        if (editIsEmpty(etRemarks,"请输入备注!")){
                            submit("AbortLot","HIK.PdaTrackAbort");
                        }
                    }
                });

                break;
            case R.id.bottom_tv2:
                if (emptyCarrier(graphiteBoatAdapter.getData())){
                    searchCarrier("","ok");
                }else {
                    showConfirmDialog("石墨舟绑定载具数量不能为空!");
                }

                break;
        }
    }

    private boolean emptyCarrier(List<XGrapHiteBoatBean> data) {
        for (XGrapHiteBoatBean bean : data){
            if (!FreeApi_StringUtils.isEmpty(bean.getReleaseCarrierId()) & !FreeApi_StringUtils.isEmpty(bean.getReleaseCarrierSeq()) & !FreeApi_StringUtils.isEmpty(bean.getWaferId())){
                return true;
            }
        }
        return false;
    }

    private void submit(String submitType, String messageName){
        DialogUtils.showLoginDialog(this, Constant.CURRENT_USER, new DialogUtils.signCallback() {
            @Override
            public void onSignSuccess() {
                JsonObject map = new JsonObject();
                JsonObject json = new JsonObject();
                json.add("XGrapHiteBoat",new JsonParser().parse(new Gson().toJson(graphiteBoatAdapter.getData())).getAsJsonArray());
                map.addProperty("lotId",lotNum);
                map.addProperty("mainEquipmentId",trackOutLoadBean.getMainEquipments());
                map.add("xGrapHiteBoats",json);
                map.addProperty("comment",etRemarks.getText().toString().trim());
                map.addProperty("operationType",submitType);

                NetUtils.requestDara(messageName,this,map,new FreeUI_DialogEntityCallBack<BaseResponseBean<TrackOutSubmitBean>>(
                        new TypeToken<BaseResponseBean<TrackOutSubmitBean>>() {
                        }.getType(), getSupportFragmentManager(), this){

                    @Override
                    public void onSuccess(Response<BaseResponseBean<TrackOutSubmitBean>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())) {
                            if (submitType.equals("Comment")){
                                String nextStepName = response.body().getBody().getNextStepDesc();
                                if (FreeApi_StringUtils.isEmpty(nextStepName)){
                                    showConfirmDialog(Work_GraphiteBoatTrackOutActivity.this,"出站成功，没有下一道工序");
                                }else {
                                    showConfirmDialog(Work_GraphiteBoatTrackOutActivity.this,"出站成功，下一道工序是" + nextStepName);
                                }

                            }else {
                                showConfirmDialog(Work_GraphiteBoatTrackOutActivity.this,"退站成功");
                            }

                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<TrackOutSubmitBean>> response) {
                        super.onError(response);
                        loadError(response.getException(),messageName);
                    }
                });
            }
        },getSupportFragmentManager());

    }

    private void  searchCarrier(String carrier,String actionType) {
//        String contains = "N";
//        if (xGrapHiteBoatBeans.size() <= 0){
//            showToast("未获取到载具数据",false);
//            return;
//        }
//
//        if (position >= xGrapHiteBoatBeans.size()){
//            showToast("载具不能重复添加",false);
//            return;
//        }
//
//        for (int i = 0; i < xGrapHiteBoatBeans.size(); i++) {
//            XGrapHiteBoatBean bean = xGrapHiteBoatBeans.get(i);
//            if (bean.getReleaseCarrierId().equals(carrier) && graphiteBoatAdapter.getData().get(i).getReleaseCarrierId().length() <=0){
//                contains = "Y";
//                if (FreeApi_StringUtils.isEmpty(bean.getGraphiteCarrierId())){
//                    bean.setGraphiteCarrierId(trackOutLoadBean.getDurableId());
//                }
//                graphiteBoatAdapter.addData(position++,bean);
//                graphiteBoatAdapter.remove(position);
//                etCarrier.setText("");
//            }
//        }
//
//        if (contains.equals("N")){
//            etCarrier.setText("");
//            etCarrier.requestFocus();
//            showToast("载具未在当前批次内或载具已添加",false);
//        }

        JsonObject map = new JsonObject();
        JsonObject json = new JsonObject();
        map.addProperty("lotId",lotNum);
        map.addProperty("actionType",actionType);
        map.addProperty("releaseId",carrier);
        json.add("XGrapHiteBoat",new JsonParser().parse(new Gson().toJson(graphiteBoatAdapter.getData())).getAsJsonArray());
        map.add("xGrapHiteBoats",json);

        NetUtils.requestDara("HIK.PdaGraphiteBind",this,map,new FreeUI_DialogEntityCallBack<BaseResponseBean<GraphiteBindListBean>>(
                new TypeToken<BaseResponseBean<GraphiteBindListBean>>() {
                }.getType(), getSupportFragmentManager(), this){

            @Override
            public void onSuccess(Response<BaseResponseBean<GraphiteBindListBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())) {
                    List<XGrapHiteBoatBean> xGrapHiteBoatBeans = response.body().getBody().getxGrapHiteBoats();
                    if (actionType.equals("ok")){
                        tvAdd.setEnabled(false);
                        tvAdd.setBackgroundColor(getResources().getColor(R.color.free_ui_blue_sky_text_gray));
                        showToast("石墨舟绑定成功",true);
                        return;
                    }
                    if (xGrapHiteBoatBeans.size() > 0){
                        graphiteBoatAdapter.setNewData(xGrapHiteBoatBeans);
                    }else {
                        showToast("MES传回数据为空",false);
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<GraphiteBindListBean>> response) {
                super.onError(response);
                loadError(response.getException(),"HIK.PdaGraphiteBind");
            }
        });
    }

    private void initInclude() {
        bottomTv1.setText("出站");
        bottomTv3.setText("退站");
        bottomTv2.setText("石墨舟绑定");
        bottomTv1.setTag("TrackOut");
        bottomTv2.setTag("TrackExit");
        bottomTv4.setVisibility(View.GONE);
        listTv1.setText("石墨舟载具");
        listTv2.setText("石墨舟载具位置");
        listTv3.setText("释放载具");
        listTv4.setText("释放载具位置");
        listTv5.setText("WaferID");
        listTv1.setVisibility(View.VISIBLE);
        listTv2.setVisibility(View.VISIBLE);
        listTv3.setVisibility(View.VISIBLE);
        listTv4.setVisibility(View.VISIBLE);
        listTv5.setVisibility(View.VISIBLE);
    }

}
